/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tela.iptsp;

import ferramentas.Query;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import tela.iptsp.modelo.InscritoIPTSP;

/**
 *
 * @author Lauro
 */
public class dadosInscritoIPTSP2 extends HttpServlet {

    //private String defaultEncoding = "ISO-8859-1";
    private String defaultEncoding = "UTF-8";

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding(defaultEncoding);
        response.setContentType("application/rss+xml;charset="+defaultEncoding);
        PrintWriter out = response.getWriter();
        try {
            String cpf = request.getParameter("cpf");
            cpf = cpf.replaceAll("\\.", "");
            cpf = cpf.replaceAll("-", "");

            Query q = new Query();

            boolean isCadastrado = false;
            if (!cpf.isEmpty()) {
                isCadastrado = q.isUsuarioCadastradoIPTSP2(cpf);
            }

            if (isCadastrado) {
                InscritoIPTSP inscrito = q.getInscritoIPTSP2porCPF(cpf);
                String xml = gerarXML(inscrito);
                //System.out.println(xml);
                out.println(xml);
            } else {
                // XML vazio pois não encontrou cpf cadastrado
                String xml = gerarXMLVazio();
                out.println(xml);
            }
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(dadosInscritoIPTSP2.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerConfigurationException ex) {
            Logger.getLogger(dadosInscritoIPTSP2.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(dadosInscritoIPTSP2.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(dadosInscritoIPTSP2.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    public String gerarXML(InscritoIPTSP inscrito)
            throws javax.xml.parsers.ParserConfigurationException,
            javax.xml.transform.TransformerException,
            javax.xml.transform.TransformerConfigurationException {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        DOMImplementation impl = builder.getDOMImplementation();

        Document doc = impl.createDocument(null, null, null);
        Element usuario = doc.createElement("usuario");
        doc.appendChild(usuario);

        Element cpf = doc.createElement("cpf");
        usuario.appendChild(cpf);
        cpf.setTextContent(inscrito.getCpf());

        Element nome = doc.createElement("nome");
        usuario.appendChild(nome);
        nome.setTextContent(inscrito.getNome());

        Element rua = doc.createElement("rua");
        usuario.appendChild(rua);
        rua.setTextContent(inscrito.getRua());

        Element complemento = doc.createElement("complemento");
        usuario.appendChild(complemento);
        complemento.setTextContent(inscrito.getComplemento());

        Element bairro = doc.createElement("bairro");
        usuario.appendChild(bairro);
        bairro.setTextContent(inscrito.getBairro());

        Element cidade = doc.createElement("cidade");
        usuario.appendChild(cidade);
        cidade.setTextContent(inscrito.getCidade());

        Element estado = doc.createElement("estado");
        usuario.appendChild(estado);
        estado.setTextContent(inscrito.getEstado());

        Element cep = doc.createElement("cep");
        usuario.appendChild(cep);
        String cepS = inscrito.getCep().substring(0, 5) + "-"+inscrito.getCep().substring(5, 8);
        cep.setTextContent(cepS);

        Element telefoneResidencial = doc.createElement("telefoneResidencial");
        usuario.appendChild(telefoneResidencial);
        telefoneResidencial.setTextContent(inscrito.getTelefone_residencial());

        Element telefoneCelular = doc.createElement("telefoneCelular");
        usuario.appendChild(telefoneCelular);
        telefoneCelular.setTextContent(inscrito.getTelefone_celular());

        Element email = doc.createElement("email");
        usuario.appendChild(email);
        email.setTextContent(inscrito.getEmail());
        
        Element polo = doc.createElement("polo");
        usuario.appendChild(polo);
        polo.setTextContent(inscrito.getPolo());

        // transform the Document into a String
        DOMSource domSource = new DOMSource(doc);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, defaultEncoding);
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        java.io.StringWriter sw = new java.io.StringWriter();
        StreamResult sr = new StreamResult(sw);
        transformer.transform(domSource, sr);
        String xml = sw.toString();
        return xml;
    }
    public String gerarXMLVazio()
            throws javax.xml.parsers.ParserConfigurationException,
            javax.xml.transform.TransformerException,
            javax.xml.transform.TransformerConfigurationException {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        DOMImplementation impl = builder.getDOMImplementation();

        Document doc = impl.createDocument(null, null, null);
        Element usuario = doc.createElement("usuario");
        doc.appendChild(usuario);

        Element cpf = doc.createElement("cpf");
        usuario.appendChild(cpf);
        cpf.setTextContent("");

        Element nome = doc.createElement("nome");
        usuario.appendChild(nome);
        nome.setTextContent("CPF não encontrado!");

        Element rua = doc.createElement("rua");
        usuario.appendChild(rua);
        rua.setTextContent("CPF não encontrado!");

        Element complemento = doc.createElement("complemento");
        usuario.appendChild(complemento);
        complemento.setTextContent("CPF não encontrado!");

        Element bairro = doc.createElement("bairro");
        usuario.appendChild(bairro);
        bairro.setTextContent("CPF não encontrado!");

        Element cidade = doc.createElement("cidade");
        usuario.appendChild(cidade);
        cidade.setTextContent("CPF não encontrado!");

        Element estado = doc.createElement("estado");
        usuario.appendChild(estado);
        estado.setTextContent("CPF não encontrado!");

        Element cep = doc.createElement("cep");
        usuario.appendChild(cep);
        cep.setTextContent("00000-000");

        Element telefoneResidencial = doc.createElement("telefoneResidencial");
        usuario.appendChild(telefoneResidencial);
        telefoneResidencial.setTextContent("(00)0000-0000");

        Element telefoneCelular = doc.createElement("telefoneCelular");
        usuario.appendChild(telefoneCelular);
        telefoneCelular.setTextContent("(00)0000-0000");

        Element email = doc.createElement("email");
        usuario.appendChild(email);
        email.setTextContent("CPF não encontrado!");
        
        Element polo = doc.createElement("polo");
        usuario.appendChild(polo);
        polo.setTextContent("0");

        // transform the Document into a String
        DOMSource domSource = new DOMSource(doc);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, defaultEncoding);
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        java.io.StringWriter sw = new java.io.StringWriter();
        StreamResult sr = new StreamResult(sw);
        transformer.transform(domSource, sr);
        String xml = sw.toString();
        return xml;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
